--
-- @Author:      
-- @DateTime:    2018-03-30 23:05:48
-- @Description: 消息的派发

local skynet = require "skynet"
local queue = require "skynet.queue"



local MessageDispatch = class("MessageDispatch")
---------------------------------------------------------
-- Private
---------------------------------------------------------
function MessageDispatch:ctor()
	self.all_msg_callback = nil
	self.tb_self_msg = {} --本服务要监听的消息
	-- self.mqueue = queue()
	
	self:registerSelf('hotfix', handler(self,self.hotfixFile))	--热更文件
end

-- 注册本服务消息
function MessageDispatch:register(callback)
	self.all_msg_callback = callback
end

--注册本服务里的消息
function MessageDispatch:registerSelf(msg_name, callback)
	if not callback or type(callback) ~= 'function' then 
		error_log("注册的函数回调不对___", msg_name)
		return
	end
	self.tb_self_msg[msg_name] = callback
end

-- --消息进行队列化
-- function MessageDispatch:queueMessage(session, source, cmd, ...)		
-- 	local func = handler(self, self.dispatchMessage)
-- 	local result = self.mqueue(func,session, source, cmd, ...)
	
-- 	return result
-- end	

--服务器消息派发
function MessageDispatch:dispatchMessage(session, source, cmd, ... )
	-- print("####dispatchMessage#######",session,source, cmd, ...)
	local func = self.tb_self_msg[cmd] -- 
	if not func and not self.all_msg_callback then 
		-- print("__self.tb_self_msg__",self.tb_self_msg)
		error_log("####### cmd "..cmd .." not found at service ", ... )		
		return
	end

	local ok = nil
	local res = false
	if cmd == "socket" then
		if func then			
			ok, res = xpcall(func, debug.traceback, source, ...)			
		else
			ok, res = xpcall(self.all_msg_callback, debug.traceback, source, ...) 			
		end
		if not ok then 
			print("____1_____dispatchMessage___error___", res)
			return 
		end
		skynet.retpack(res)
		return true
	end
	
	if func then
		if not session and not source then 
			return func(...)
		end
		ok, res = xpcall(func, debug.traceback, ...)	
	else
		ok, res = xpcall(self.all_msg_callback, debug.traceback, cmd, ...) 	
	end
	if not ok then 
		print("_____2____dispatchMessage___error___", res)
		return 
	end	
	skynet.retpack(res)
end

--自己节点内消息派发
function MessageDispatch:dispatchSelfMessage(cmd, ... )
	-- log.debug("####dispatchSelfMessage#######", cmd, ...)
	print("_______自己节点内消息派发______",cmd,...)
	local func = self.tb_self_msg[cmd] -- gate是否有handler
	if not func and not self.all_msg_callback then 
		error_log("####### cmd "..cmd .." not found at manager_service ")
		return
	end
	
	if func then
		return func(...)
	else
		return self.all_msg_callback(...)
	end
end


-- --需要排队的消息
-- function MessageDispatch:dispatchQueue()
-- 	return handler(self, self.queueMessage)
-- end

function MessageDispatch:dispatch(type)
	return handler(self, self.dispatchMessage)
end

function MessageDispatch:hotfixFile(file_name)
    debug_log("____hotfix_____", file_name )
    if global and global.hotfix then 
    	return global.hotfix:hotfixFile(file_name)
   	end
   	return true
end 

return MessageDispatch